<?php
namespace app\user\controller;
use think\Controller;
use app\common\entity\RequestEntity;
use app\common\controller\ResponseJson;
use think\Db;
use think\Session;

class Login extends Controller{
    public $USER_INFO = null;
    public function Index(){
        $Account = new RequestEntity('Account','账号',true,32);
        $Password = new RequestEntity('Password','密码',true,32);
        if(empty($Account->text)){
            $this->ResponseJson(null,'用户名不能为空');
        }
        if(empty($Password->text)){
            $this->ResponseJson(null,'密码不能为空');
        }
        //查找用户信息，在登录用户名密码正确的情况下
        $UserInfo = Db::table('staff')
            ->field(
                [
                    'staff_id'=>'Id',
                    'account'=>'Account',
                    'password'=>'Password',
                    'nick_name'=>'NickName',
                    'pic_url'=>'PicUrl',
                    'number'=>'Number',
                    'gender'=>'Sex',
                    'phone_number'=>'Phone',
                    'department_id'=>'Depart'
                ]
            )
            ->where(
                [
                    'account'=>$Account->text,
                    'password'=>md5($Password->text),
                    'status'=>1
                ]
            )
            ->find();
//        var_dump($UserInfo);exit;
        //如果用户名密码正确 则有用户信息
        if($UserInfo){
            $UserToken = $this->GenerateToken($UserInfo);
            //将token存入缓存
            Session::set('LoginToken',$UserToken);
            $UserArray['token'] = $UserToken;
            //登录后用户误操作 过期时间
            $UserArray['token_expire'] = time() + (int)3600;
            $UserArray['department_id'] = $UserInfo['Depart'];
            $UserArray['login_ip'] = $this->GetIp();
            $UserArray['login_time'] = date('Y-M-D H:i:s',time());
            $RoleId = Db::table('staff_role')
                ->field(
                    [
                        'role_id'=>'RoleId'
                    ]
                )
                ->where(
                    ['staff_id'=>$UserInfo['Id']]
                )
                ->find();
            Session::set('RoleId',$RoleId['RoleId']);
            $this->USER_INFO = $UserArray;
            Session::set('UserInfo',$UserArray);
            Db::table('staff')
                ->where([
                    'staff_id' => $UserInfo['Id'],
                ])
                ->update($UserArray);
//            echo "登录成功";
            $result = [
                'Code'=>200,
                'Message'=>'登录成功',
                'Uid'=>$UserInfo['Id'],
                'RoleId'=>$RoleId['RoleId'],
                'NickName'=>$UserInfo['NickName'],
                'PicUrl'=>HttpPath.$UserInfo['PicUrl']
            ];
            return ResponseJson::Json($result);
        }else{
            $this->ResponseJson(null, '用户名或密码错误');
        }
    }
    public function Logout(){
        session('LoginToken', null);
        Session::set('UserInfo',null);
        $resultset_userinfo['Token'] = null;
        $resultset_userinfo['ip'] = null;
        $response_json['UserInfo'] = $resultset_userinfo;
        $this->ResponseJson($response_json);
    }
    /**
     * 生成token
     * @return string
     */
    public function GenerateToken($UserInfo){
        return MD5($UserInfo['Id'] . $UserInfo['Account'] . time());
    }

    /**
     * @param $param_userinfo
     * @return string
     */
    public static function GetTimestamp($param_hour)
    {
//        return time() + 100;
        return time() + $param_hour * 60 * 60;
    }

    /**
     * 响应数据请求，返回Json数据
     * @param null $param_items 待返回数据数组
     * @param string $param_message 数据状态说明
     * @return string
     */
    public function ResponseJson($param_items = null, $param_message = 'Error')
    {
        if (!isset($param_items)) {
            $array_result['State']['Code'] = 0;
            $array_result['State']['Message'] = $param_message;
            exit(json_encode($array_result));
        } else {
            if($param_items==1||$param_items==0){
                $array_result['State']['Code'] = 1;
                $array_result['State']['Message'] = 'Success';
                exit(json_encode($array_result));
            }
            else if($param_items=='timeout'){
                $array_result['State']['Code'] = -1;
                $array_result['State']['Message'] = 'Token Timeout';
                exit(json_encode($array_result));
            }
            else{
                $array_result['State']['Code'] = 1;
                $array_result['State']['Message'] = 'Success';
                exit(json_encode(array_merge($array_result, $param_items)));
            }
        }
    }
    /*
 * 获取用户ip地址
 */
    public function GetIp()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return ($ip);
    }
}